package com.gem.talkbase.util;

import java.util.ArrayList;
import java.util.List;

import com.gem.talkbase.bean.ChatMsg;



import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MessageDB {
	private SQLiteDatabase db;

	public MessageDB(Context context) {
		db = context.openOrCreateDatabase("message1.db",
				Context.MODE_PRIVATE, null);
	}

	public void saveMsg(String whosend, ChatMsg entity) {
		db.execSQL("CREATE table IF NOT EXISTS _"
				+ whosend
				+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,date TEXT,from_ TEXT,message TEXT)");
//		String from = "OUT";
//		if (entity.getFrom()!=null) {//如果是收到的消息，保存在数据库的值为1
//			from = "IN";
//		}
		db.execSQL(
				"insert into _" + whosend
						+ " (name,date,from_,message) values(?,?,?,?)",
				new Object[] { entity.getUserid(),
						entity.getDate(),entity.getFrom(), entity.getMsg() });
	}

	public List<ChatMsg> getMsg(String whosend) {
		List<ChatMsg> list = new ArrayList<ChatMsg>();
		db.execSQL("CREATE table IF NOT EXISTS _"
				+ whosend
				+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, date TEXT,from_  TEXT,message TEXT)");
		Cursor c = db.rawQuery("SELECT * from _" + whosend + " ORDER BY _id DESC LIMIT 5", null);
		while (c.moveToNext()) {
			String name = c.getString(c.getColumnIndex("name"));
			String date = c.getString(c.getColumnIndex("date"));
			String from = c.getString(c.getColumnIndex("from_"));
			String message = c.getString(c.getColumnIndex("message"));
			ChatMsg entity = new ChatMsg(name, message, date, 
					from);
			list.add(entity);
		}
		c.close();
		return list;
	}

	public void close() {
		if (db != null)
			db.close();
	}
}

